﻿using AutoMapper;
using B.S.BaseData.suyuan.ApiWrite.Account.Command;
using B.S.BaseData.suyuan.InforStances.Interface;
using B.S.BaseData.Suyuan.Command;
using B.S.BaseData.Suyuan.Dommain;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BaseData.suyuan.ApiWrite.Account.CommandHeader
{
    public class DeleteCommandHeader : IRequestHandler<DeleteCommand, ApiResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<JiBeninformation> jibenBase;

        public DeleteCommandHeader(IMapper mapper, IBaseRepository<JiBeninformation> jibenBase)
        {
            this.mapper = mapper;
            this.jibenBase = jibenBase;
        }
        /// <summary>
        /// 删除基本信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<object>> Handle(DeleteCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            int successCount = 0;

            // 遍历要删除的Id集合
            foreach (var id in request.Ids)
            {
                var obj = await jibenBase.IQueryEntity().Result.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
                if (obj != null)
                {
                    obj.Isdel = 0;
                    var res = await jibenBase.DeleEntity(obj);
                    if (res == 1)
                    {
                        successCount++;
                    }
                }
            }
            if (successCount == request.Ids.Count)
            {
                result.Code = APIEnum.删除成功;
                result.Msg = APIEnum.删除成功.ToString();
                result.data = successCount.ToString();
            }
            else if (successCount > 0)
            {
                result.Code = APIEnum.部分删除成功;
                result.Msg = $"部分删除成功，共删除了 {successCount} 条记录";
                result.data = successCount.ToString();
            }
            else
            {
                result.Code = APIEnum.删除失败;
                result.Msg = APIEnum.删除失败.ToString();
                result.data = "0";
            }

            return result;
        }
    }
}
